package com.hung.pro.iFlashCards;

import com.hung.pro.iFlashCards.bean.LexiconBean;
import com.hung.pro.iFlashCards.component.DefaultListCellEditor;
import com.hung.pro.iFlashCards.component.DefaultMutableListModel;
import com.hung.pro.iFlashCards.component.JListMutable;
import com.hung.pro.iFlashCards.dao.LexiconBeanDao;
import com.hung.pro.iFlashCards.ui.Resources;
import com.hung.pro.iFlashCards.ui.UIHelper;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.uif_lite.panel.SimpleInternalFrame;

import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: hung
 * Date: 2008/05/02
 * Time: 0:02:05
 * To change this template use File | Settings | File Templates.
 */
public class EditLexiconWindow extends JDialog {
    private JPanel mainPanel;
    private JPanel rightPanel;
    private JButton addButton;
    private JButton deleteButton;
    private JScrollPane scrollPane;
    private JButton editVocabularyButton;
    private JListMutable lexiconList;

    /**
     * lexicon dao
     */
    private static LexiconBeanDao lexiconDao = new LexiconBeanDao();
    /**
     * keep data of the list
     */
    private DefaultMutableListModel dataModel;

    public EditLexiconWindow() throws Exception {
        super();
        setupUI();

        init();
    }

    private void createUIComponents() {

        dataModel = new DefaultMutableListModel();
        /* for (int i = 0; i < 100; i++)
     dataModel.addElement(new LexiconBean("xxx" + String.valueOf(i)));*/
        lexiconList = new JListMutable(dataModel);
        lexiconList.setVisibleRowCount(-1);
        lexiconList.setListCellEditor(new DefaultListCellEditor(new JTextField()));
        scrollPane = new JScrollPane(lexiconList);
        //scrollPane.add(lexiconList);
        dataModel.addListDataListener(new LexiconListDataListener());
        lexiconList.addListSelectionListener(new LexiconListSelectionListener());


    }

    /**
     * get data in db and display on list
     */
    private void init() throws Exception {
        try {
            deleteButton.setEnabled(false);
            editVocabularyButton.setEnabled(false);
            deleteButton.addActionListener(new DeleteButtonActionListener());
            addButton.addActionListener(new AddButtonActionListner());
            editVocabularyButton.addActionListener(new EditVocabularyButtonActionListener());
            //connect to db
            if (!lexiconDao.connect()) {
                throw new Exception("Can't not connect to DB");
            }
            List<LexiconBean> lexiconListData = lexiconDao.getLexicon();
            for (LexiconBean lexicon : lexiconListData) {
                dataModel.addElement(lexicon);
            }

        }
        catch (Exception ex) {
            throw ex;
        }
    }

    public void showWindow() {
        try {
            String selectedLaf = UIManager.getSystemLookAndFeelClassName();

            try {
                UIManager.setLookAndFeel(selectedLaf);
            } catch (Exception e) {
                System.out.println("Can't change L&F: " + e);
            }
            this.setTitle(Resources.getString("window.title.edit.lexicon"));
            this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            SimpleInternalFrame sif = new SimpleInternalFrame("Learn@pro");
            sif.setContent(new EditLexiconWindow().mainPanel);
            this.setContentPane(sif);
            //set window size
            this.setSize(new Dimension(700, 400));
            //centerlized window
            this.setLocationRelativeTo(null);
            this.setIconImage(UIHelper.readImageIcon("app.png").getImage());
            this.setLocale(Resources.getLocale());
            this.setVisible(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void setupUI() {
        createUIComponents();
        mainPanel = new JPanel();
        mainPanel.setLayout(new FormLayout("fill:342px:grow,left:4dlu:noGrow,fill:118px:noGrow", "center:d:grow,bottom:d:noGrow"));
        CellConstraints cc = new CellConstraints();
        mainPanel.add(scrollPane, cc.xywh(1, 1, 1, 2, CellConstraints.FILL, CellConstraints.FILL));
        rightPanel = new JPanel();
        rightPanel.setLayout(new FormLayout("fill:d:grow", "center:d:noGrow,top:4dlu:noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:max(d;4px):noGrow"));
        rightPanel.setMinimumSize(new Dimension(130, 100));
        rightPanel.setPreferredSize(new Dimension(130, 100));
        mainPanel.add(rightPanel, cc.xy(3, 1, CellConstraints.DEFAULT, CellConstraints.FILL));
        addButton = new JButton();
        UIHelper.setMenuItemText(addButton, Resources.getString("button.lexicon.add"));
        rightPanel.add(addButton, cc.xy(1, 1));
        deleteButton = new JButton();
        UIHelper.setMenuItemText(deleteButton, Resources.getString("button.lexicon.delete"));
        rightPanel.add(deleteButton, cc.xy(1, 5));
        editVocabularyButton = new JButton();
        UIHelper.setMenuItemText(editVocabularyButton, Resources.getString("button.lexicon.edit"));
        rightPanel.add(editVocabularyButton, cc.xy(1, 3));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return mainPanel;
    }

    /**
     * Close window
     */

    /******Listener*****************/
    /**
     * Listen data changed event of LexiconList
     */
    class LexiconListDataListener implements ListDataListener {

        public void intervalAdded(ListDataEvent e) {

        }

        public void intervalRemoved(ListDataEvent e) {

        }

        public void contentsChanged(ListDataEvent e) {

            DefaultMutableListModel model = (DefaultMutableListModel) e.getSource();
            Object obj = model.get(e.getIndex0());
            if (!(obj instanceof LexiconBean)) {
                return;
            }
            LexiconBean lexicon = (LexiconBean) obj;
            if (lexicon.getName() == null || "".equals(lexicon.getName())) {
                return;
            }
            try {

                if (lexicon.getId() == -1) {
                    int id = lexiconDao.insertLexicon(lexicon);
                    lexicon.setId(id);
                } else {
                    lexiconDao.updatetLexicon(lexicon);
                }
            }
            catch (SQLException ex) {
                String error = Resources.getString("message.insert.duplicate");
                JOptionPane.showMessageDialog(mainPanel.getParent(), error, "Error", JOptionPane.WARNING_MESSAGE);
            }
            catch (Exception ex) {
                String error = ex.getLocalizedMessage();
                JOptionPane.showMessageDialog(mainPanel.getParent(), error, "Error", JOptionPane.WARNING_MESSAGE);
            }
        }
    }

    class LexiconListSelectionListener implements ListSelectionListener {
        //Listener method for list selection changes.
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {

                if (lexiconList.getSelectedIndex() == -1) {
                    //No selection: disable delete, up, and down buttons.
                    deleteButton.setEnabled(false);
                    editVocabularyButton.setEnabled(false);

                } else if (lexiconList.getSelectedIndices().length > 1) {
                    //Multiple selection: disable up and down buttons.
                    deleteButton.setEnabled(true);
                    editVocabularyButton.setEnabled(true);


                } else {
                    //Single selection: permit all operations.
                    deleteButton.setEnabled(true);
                    editVocabularyButton.setEnabled(true);

                }
            }
        }
    }

    /**
     * Add button actionlistener
     */
    class AddButtonActionListner implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //add new lexicon
            LexiconBean lexicon = new LexiconBean("New Lexicon");
            dataModel.addElement(lexicon);
            int size = dataModel.getSize();
            lexiconList.setSelectionInterval(size - 1, size - 1);
            lexiconList.requestFocus();
            //start edit cell, make it editable
            lexiconList.editCellAt(size - 1, null);
            JTextField cellEditor = (JTextField) lexiconList.getEditorComponent();
            cellEditor.requestFocus();
            //select all text in the textbox
            cellEditor.selectAll();
            System.out.println("Add new ");
        }
    }

    /**
     * Delete button action listener
     */
    class DeleteButtonActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String msg = Resources.getString("message.delete.lexicon.warn");
            int confirmRet = JOptionPane.showConfirmDialog(mainPanel.getParent(), msg, "Confirm", JOptionPane.YES_NO_OPTION);
            if (JOptionPane.NO_OPTION == confirmRet) {
                return;
            }
            try {
//delete from DB
                List<LexiconBean> deleteLexiconList = new ArrayList<LexiconBean>();
                //delete from db
                int[] selectedIndexes = lexiconList.getSelectedIndices();
                for (int i = 0; i < selectedIndexes.length; i++) {
                    LexiconBean lexicon = (LexiconBean) dataModel.get(selectedIndexes[i]);
                    deleteLexiconList.add(lexicon);
                }
                lexiconDao.deleteMultiLexiconItems(deleteLexiconList);
                //remove from list
                for (LexiconBean lexicon : deleteLexiconList) {
                    dataModel.removeElement(lexicon);
                }
            } catch (Exception e1) {
                String error = e1.getLocalizedMessage();
                JOptionPane.showMessageDialog(mainPanel.getParent(), error, "Error", JOptionPane.WARNING_MESSAGE);
                e1.printStackTrace();
            }

        }
    }

    private class EditVocabularyButtonActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
//delete from DB
                List<LexiconBean> deleteLexiconList = new ArrayList<LexiconBean>();
                //delete from db
                int selectedIndex = lexiconList.getSelectedIndices()[0];
                LexiconBean lexicon = (LexiconBean) dataModel.get(selectedIndex);
                //show Edit vocabulary
                EditVocabularyWindow editVocabularyWnd = new EditVocabularyWindow();
                editVocabularyWnd.setModal(true);
                editVocabularyWnd.setCurrentLexiconId(lexicon.getId());
                editVocabularyWnd.showWindow();

            } catch (Exception e1) {
                String error = e1.getLocalizedMessage();
                JOptionPane.showMessageDialog(mainPanel.getParent(), error, "Error", JOptionPane.WARNING_MESSAGE);
                e1.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        try {
            EditLexiconWindow editLexiconWnd = new EditLexiconWindow();
            editLexiconWnd.showWindow();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
